<template>
  <PageContainer>
    <view class="container">
      <Header title="发送合作意向">
        <CustomTopTips text="收集内容来源于供需发布者配置，请尽量填写完整" />
      </Header>
      <BasicsForm
        style="background-color: #fff"
        :schemas="schemas"
        @register="register"
        @submit="onSubmit"
      />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* applyDirectCooperation 申请直接合作 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import CustomTopTips from '@/components/CustomTopTips/index.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormSchema } from '@/components/Form';
  import { navigateTo, onLoad, redirectTo } from '@/router';
  import { ref } from 'vue';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import { forEach, isArray } from 'lodash-es';
  import type { ApplyCooperation } from '@/router/types/modules';
  import { ApplicationTypeEnum } from '@/enums/businessOpportunitiesEnum';
  import { supplyDemandFormDetails, supplyDemandFormSubmit } from '@/api/businessOpportunities';
  import type { SubmitAnswerListItem } from '@/api/membership/formCompTypes';
  import type { CardBottomBtnsOptions } from '@/components/TButtonGroup/types';
  import { SupplyDemandFormAnswerCacheKey } from '../../components/utils';
  import { onShow } from '@dcloudio/uni-app';

  const schemas = ref<FormSchema[]>([]);
  const btnGroupOptions = ref<CardBottomBtnsOptions>({
    styles: {
      backgroundColor: '#fff',
    },
    submit: {
      text: '提交',
      customStyle: {
        backgroundColor: '#2878FF',
        color: '#fff',
        borderRadius: '44rpx',
      },
    },
  });

  const [register, {}] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    validateTrigger: 'bind',
    btnGroupOptions: btnGroupOptions,
  });

  const routeOptions = ref<ApplyCooperation>();
  onLoad<'applyDirectCooperation'>(async (op) => {
    routeOptions.value = op;

    if (op.type === ApplicationTypeEnum.match) btnGroupOptions.value.submit!.text = '下一步';

    const res = await supplyDemandFormDetails(op.id!);
    const list: FormSchema[] = [];
    forEach(res.formItemList, (v) => {
      const field = v.id.toString();
      const answer = v.formUserItemAnswerList;
      const defaultValue = isArray(answer) ? answer[answer.length - 1].content : '';

      list.push({
        field,
        label: v.showName,
        component: v.itemType,
        required: !!v.isRequired,
        defaultValue,
        rules: [
          {
            required: !!v.isRequired,
            errorMessage: v.value || v.showName,
          },
        ],
        componentProps: {
          placeholder: v.value,
          limit: v.itemType === 'UploadImg' ? 9 : void 0,
          localdata: localDataMapping(v.customFormItemAnswerList || [], {
            label: 'words',
            value: 'id',
          }),
        },
      });
    });
    schemas.value = list
  });

  function onSubmit(vals: Recordable) {
    if (!routeOptions.value) return;

    const answerList: SubmitAnswerListItem[] = [];
    for (const key in vals) {
      let content = vals[key];
      if (!isArray(content)) content = content.toString().split(',');
      const answerItem: SubmitAnswerListItem = {
        formItemId: key,
        content,
      };
      answerList.push(answerItem);
    }

    routeOptions.value.type === ApplicationTypeEnum.direct
      ? handleDirect(answerList)
      : handleMatch(answerList);
  }

  // 直达
  async function handleDirect(answerList: SubmitAnswerListItem[]) {
    if (!routeOptions.value) return;
    const res = await supplyDemandFormSubmit({
      boInfoId: routeOptions.value.id,
      boContactType: ApplicationTypeEnum.direct,
      shareKey: routeOptions.value.shareKey,
      customFormItem: {
        customFormId: routeOptions.value.id!,
        answerList,
      },
    });

    redirectTo({
      name: 'applyCooperationResult',
      options: {
        id: res.id,
        type: routeOptions.value.type,
        boInfoId: routeOptions.value.id!,
      },
    });
  }

  // 秘书处撮合
  function handleMatch(answerList: SubmitAnswerListItem[]) {
    if (!routeOptions.value) return;
    uni.setStorageSync(SupplyDemandFormAnswerCacheKey, answerList);
    navigateTo({
      name: 'requestAdminMatch',
      options: {
        id: routeOptions.value.id,
        type: routeOptions.value.type,
        shareKey: routeOptions.value.shareKey,
      },
    });
  }

  onShow(() => {
    uni.removeStorageSync(SupplyDemandFormAnswerCacheKey);
  });
</script>

<style lang="scss" scoped></style>
